package com.hkbigdata.window;

import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;

import java.util.Arrays;

/**
 * @author liuanbo
 * @creat 2024-04-26-9:50
 * @see 2194550857@qq.com
 */
public class Flink05_ProcessTime_ReduceFunction_TimeWindows {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);

        SingleOutputStreamOperator<Tuple2<String, Integer>> flatMap = env.socketTextStream("hadoop102", 9999)
                .flatMap((String data, Collector<Tuple2<String, Integer>> out) -> {
                    String[] split = data.split(",");
                    Arrays.stream(split).forEach(word -> out.collect(Tuple2.of(word, 1)));
                }).returns(Types.TUPLE(Types.STRING, Types.INT));
        flatMap.keyBy(data -> data.f0)
                .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<Tuple2<String, Integer>>() {
                    @Override
                    public Tuple2<String, Integer> reduce(Tuple2<String, Integer> value1, Tuple2<String, Integer> value2) throws Exception {
                        return new Tuple2<>(value1.f0, value1.f1 + value2.f1);
                    }
                }).print();

        env.execute();
    }
}
